package cn.wolfcode.luowowo.website.web.controller;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.cache.service.IStrategyStatisVOService;
import cn.wolfcode.luowowo.cache.service.ITravelStatisVOService;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.cache.vo.TravelStatisVO;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.web.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.web.annotation.UserParam;
import cn.wolfcode.luowowo.website.web.util.UMEditorUploader;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/travel")
public class TravelController {
    @Reference
    private ITravelService travelService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private IStrategyDetailService strategyDetailService;
    @Reference
    private IUserInfoRedisService userInfoRedisService;
    @Reference
    private ITravelCommentService travelCommentService;
    @Reference
    private IStrategyStatisVOService strategyStatisVOService;

    @Reference
    private ITravelStatisVOService travelStatisVOService;

    @RequestMapping("")
    public String list(Model model, @ModelAttribute("qo") TravelQuery qo) {
        model.addAttribute("pageInfo", travelService.query(qo));
        //拓展:游记首页里面最新游记评论动态(前10个)
        model.addAttribute("tcs", travelCommentService.queryCommentForTen(new TravelCommentQuery()));
        //拓展 国内最火的前十攻略 根据阅读量

        model.addAttribute("travelTen", strategyStatisVOService.queryChinaStrategyForTenByViewnum());
        //model.addAttribute("travelTen", strategyStatisVOService.queryChinaCommends());
        return "travel/list";
    }


    @RequestMapping("/detail")
    public String detail(Model model, Long id, @UserParam UserInfo userInfo) {
        //detail
        Travel t = travelService.get(id);
        t.setTravelContent(travelService.getContent(id));
        model.addAttribute("detail", t);
        //toasts
        List<Destination> toasts = destinationService.getToasts(t.getDest().getId());
        Destination dest = toasts.remove(toasts.size() - 1);
        model.addAttribute("toasts", toasts);
        model.addAttribute("dest", dest);
        //sds 相关攻略
        model.addAttribute("sds", strategyDetailService.getViewNumTop3(t.getDest().getId()));
        //ts 相关游记
        model.addAttribute("ts", travelService.getViewNumTop3(t.getDest().getId()));
        //共享一个数据  进行判断是否与作者为同一人  如果不是一样  不显示编辑界面
        if (userInfo != null) {
            if (t.getAuthor().getId() == userInfo.getId()) {
                model.addAttribute("ret", "gogo");
            }
            //判断登录用户是否已收藏该游记
            model.addAttribute("isFavor", travelStatisVOService.isFavor(id, userInfo.getId()));
        }
        //共享list
        TravelCommentQuery qo = new TravelCommentQuery();
        qo.setCurrentPage(1);
        qo.setPageSize(Integer.MAX_VALUE);
        qo.setTravelId(id);
        model.addAttribute("list", travelCommentService.query(qo).getContent());
        //当有用户访问具体的游记的时候 , 游记的浏览量增加一条
        travelStatisVOService.addScoreByViewnum(id, 1);
        //获取vo对象
        TravelStatisVO vo = travelStatisVOService.getTravelStatisVO(id);
        model.addAttribute("vo", vo);


        return "travel/detail";
    }

    @RequestMapping("/input")
    @RequireLogin
    public String input(Model model, Long id) {
        //tv
        if (id != null) {
            Travel travel = travelService.get(id);
            travel.setTravelContent(travelService.getContent(id));
            model.addAttribute("tv", travel);
        }
        //dests
        model.addAttribute("dests", destinationService.getDestsByDeep(3));
        return "travel/input";
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Travel travel, @UserParam UserInfo userInfo) {
        //作者
        //travel.setAuthor(userInfo);
        if (userInfo == null) {
            //没有登陆
            //throw new LogicException("请先登录,再进行操作");
        }
        travel.setAuthor(userInfo);
        Long id = travelService.saveOrUpdate(travel);
        return AjaxResult.SUCCESS.addData(id);
    }

    @RequestMapping("/commentAdd")
    public String commentAdd(Model model, TravelComment comment, int floor, @UserParam UserInfo userInfo) {
        //作者
        //travel.setAuthor(userInfo);
        if (userInfo == null) {
            //没有登陆
            throw new RuntimeException("请先登录,再进行评论操作");
        }
        comment.setLevel(userInfo.getLevel());
        comment.setCity(userInfo.getCity());
        comment.setHeadUrl(userInfo.getHeadImgUrl());
        comment.setUserId(userInfo.getId());
        comment.setUsername(userInfo.getNickname());
        //参数设置完毕之后 , 进行保存操作
        comment = travelCommentService.saveOrUpdate(comment);
        //c
        model.addAttribute("c", comment);
        //floor
        model.addAttribute("floor", travelCommentService.getCount(comment.getTravelId()));
        //评论时候 , 增加vo中的数据
        travelStatisVOService.addComment(comment.getTravelId(), 1);
        return "travel/commentTpl";
    }


    @Value("${file.path}")
    private String filePath;

    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception {
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif", ".png", ".jpg", ".jpeg", ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\"" + up.getFileName() + "\", \"originalName\": \"" + up.getOriginalName() + "\", \"size\": " + up.getSize()
                + ", \"state\": \"" + up.getState() + "\", \"type\": \"" + up.getType() + "\", \"url\": \"" + up.getUrl() + "\"}";
        result = result.replaceAll("\\\\", "\\\\");
        if (callback == null) {
            return result;
        } else {
            return "<script>" + callback + "(" + result + ")</script>";
        }
    }

    //游记  的顶操作 travelThumbup
    @RequestMapping("/travelThumbup")
    @ResponseBody
    public Object travelThumbup(Long tid, @UserParam UserInfo userInfo) {
        //tid 为哪篇游记 , 还需要知道哪个用户点击的操作  所以注入用户对象
        if (userInfo == null) {
            //如果没有登录
            AjaxResult result = new AjaxResult(false, "请先登录");
            result.setCode(AjaxResult.NO_LOGIN);
            return result;
        }
        //顶成功  ture  顶过了 false
        boolean ret = travelStatisVOService.travelThumbup(tid, userInfo.getId());

        return new AjaxResult(ret, "").addData(travelStatisVOService.getTravelStatisVO(tid));
    }

    //用户的 收藏与取消收藏的操作
    @RequestMapping("/favor")
    @ResponseBody
    public Object favor(Long tid, @UserParam UserInfo userInfo) {
        //tid 为哪篇游记 , 还需要知道哪个用户点击的操作  所以注入用户对象
        if (userInfo == null) {
            //如果没有登录
            AjaxResult result = new AjaxResult(false, "请先登录");
            result.setCode(AjaxResult.NO_LOGIN);
            return result;
        }
        //收藏成功  ture    false 取消收藏
        boolean ret = travelStatisVOService.favor(tid, userInfo.getId());

        return new AjaxResult(ret, "").addData(travelStatisVOService.getTravelStatisVO(tid));
    }

}
